/*
 * Copyright 2007 Jeffrey Palm
 */

import java.io.*;
import java.util.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.List;
import javax.microedition.midlet.*;

abstract class AbstractList extends Form {

  abstract void ok(Object value,Bloglines midlet);
  abstract void parseRest(Vector subs);
  void addRest() {}

  AbstractList(final Bloglines midlet, String title) {
    this(midlet,title,null);
  }

  protected void append(final Object val, String str) {
    if (str == null) str = "<none>";
    ObjectItem it = new ObjectItem(val,str);
    it.setItemCommandListener(new ItemCommandListener() {
	public void commandAction(Command cmd, javax.microedition.lcdui.Item it) {
	  ok(val,midlet);
	}});
    append(it);
  }

  static class ObjectCommand extends Command {
    private final Object val;
    ObjectCommand(Object val, String str) {
      super(str,Command.ITEM,1);
      this.val = val;
    }
    public Object getValue() {return val;}
  }

  static class ObjectItem extends StringItem {
    private final Object val;
    ObjectItem(Object val, String str) {
      super("",str);
      this.val = val;
      setLayout(LAYOUT_EXPAND | LAYOUT_LEFT | BUTTON | LAYOUT_NEWLINE_BEFORE);
      setDefaultCommand(new ObjectCommand(val,str));
      setFont(SMALL_FONT);
    }
    public Object getValue() {return val;}
  }

  private final Bloglines midlet;

  AbstractList(final Bloglines midlet, String title, final Displayable prev) {
    super(title);
    this.midlet = midlet;
    final Command ok = new Command("OK",Command.OK,1);
    final Command back = new Command("Back",Command.BACK,1);
    if (prev != null) addCommand(back);
    addRest();
    setCommandListener(new CommandListener() {
	public void commandAction(Command c, Displayable d) {
	  if (c == back && prev != null) {
	    midlet.setCurrent(prev);
	  } else {
	    ok(((ObjectCommand)c).getValue(),midlet);
	  }
	}
      });
  }

  private final static Font SMALL_FONT = Font.getFont(Font.FACE_PROPORTIONAL,Font.STYLE_PLAIN,Font.SIZE_SMALL);

  public final void parse(Vector subs) {
    parseRest(subs);
  }
}
